package org.ix.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.ix.common.models.IxUser;
import org.ix.shiro.model.LoginModel;
import org.ix.shiro.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody LoginModel loginModel) {
        return ResponseEntity.ok(accountService.login(loginModel));
    }

    @GetMapping("/get-current-user")
    @RequiresAuthentication()
    public ResponseEntity<IxUser> getCurrentUser() {

        IxUser user = (IxUser) SecurityUtils.getSubject().getPrincipal();
        Set<String> roles = accountService.getUserRoles(user.getId());
        Set<String> permissions = accountService.getUserPermissions(roles);

        user.setRoles(roles);
        user.setPermissions(permissions);

        return ResponseEntity.ok(user);
    }

    @GetMapping("/hello")
    public ResponseEntity<String> hello() {
        return ResponseEntity.ok("hello");
    }
}
